package com.authine.cloudpivot.app.openapi.config;

import com.authine.cloudpivot.app.openapi.repository.RouteConfigDORepository;
import com.authine.cloudpivot.app.openapi.repository.databaseobject.RouteConfigDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author carter
 * create_date  2020/6/10 14:20
 * description     初始化swagger的所有服务的路径
 */
@Slf4j
@Configuration
@Component
@Primary
public class SwaggerConfig implements SwaggerResourcesProvider {

    private final RouteConfigDORepository routeConfigDORepository;

    public SwaggerConfig(RouteConfigDORepository routeConfigDORepository) {
        this.routeConfigDORepository = routeConfigDORepository;
    }


    @Override
    public List<SwaggerResource> get() {

        List<SwaggerResource> list = new LinkedList<>();

        //找到所有的网关，然后添加到swagger的资源中；
        Optional.ofNullable(routeConfigDORepository.findAll())
                .orElse(Collections.emptyList())
                .stream()
                .filter(item -> StringUtils.isNotBlank(item.getRouteUri()))
                .filter(item -> !StringUtils.startsWith(item.getRouteId(), "app-launcher-"))
                .collect(Collectors.toMap(RouteConfigDO::getRouteId, Function.identity(), (old, ne) -> ne))
                .values()
                .forEach(config -> {
                    String applicationName = config.getRouteUri();
                    applicationName = applicationName.substring(applicationName.indexOf(":") + 3);
                    String path = "/" + applicationName.substring(applicationName.indexOf("-") + 1).replaceAll("-", "/") + "/v2/api-docs";
                    list.add(initSwaggerResource(applicationName + "-" + config.getMemo(), path));
                });

        log.info("swagger source url = {}", list.stream().map(SwaggerResource::getUrl));

        return list;
    }

    /**
     * 初始化swagger资源
     *
     * @param name     应用名称
     * @param location swagger的api-doc的路径；
     * @return swagger的备注信息
     */
    private SwaggerResource initSwaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("3.0");
        return swaggerResource;
    }

}
